package com.gutsyzhan.bilibili.aspect;

import com.gutsyzhan.bilibili.domain.annotation.ApiLimitedRole;
import com.gutsyzhan.bilibili.domain.auth.UserRole;
import com.gutsyzhan.bilibili.exception.ConditionException;
import com.gutsyzhan.bilibili.service.UserRoleService;
import com.gutsyzhan.bilibili.support.UserSupport;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Aspect
@Component
@Order(1)
public class ApiLimitedRoleAspect {
    @Resource
    private UserSupport userSupport;

    @Resource
    private UserRoleService userRoleService;

    @Pointcut("@annotation(com.gutsyzhan.bilibili.domain.annotation.ApiLimitedRole)")
    public void check(){}

    @Before("check() && @annotation(apiLimitedRole)")
    public void doBefore(JoinPoint joinPoint, ApiLimitedRole apiLimitedRole){
        Long userId = userSupport.getCurrentUserId();
        List<UserRole> userRoleList = userRoleService.getUserRoleByUserId(userId);
        String[] limitedRoleCodeList = apiLimitedRole.limitedRoleCodeList();
        Set<String> limitedRoleIdSet = Arrays.stream(limitedRoleCodeList).collect(Collectors.toSet());
        Set<String> userRoleCodeSet = userRoleList.stream().map(UserRole::getRoleCode).collect(Collectors.toSet());
        //只要用户具备的某一角色在被禁止访问的角色编码列表内，那么这个接口就无法访问
        //用户所有角色与被禁止访问的角色列表取交集，大于0则无法访问
        userRoleCodeSet.retainAll(limitedRoleIdSet);
        if(!userRoleCodeSet.isEmpty()){
            throw new ConditionException("权限不足!");
        }
    }


}
